package com.jr.Controller;

import com.google.gson.Gson;
import com.jr.Pojo.Couriers;
import com.jr.Pojo.Packages;
import com.jr.Pojo.Users;
import com.jr.Service.IAdminService;
import com.jr.Service.ICouriersService;
import com.jr.Service.Impl.AdminServiceImpl;
import com.jr.Service.Impl.CouriersServiceImpl;
import com.jr.util.PageHelper;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

@WebServlet("/admin/*")
public class AdminController extends HttpServlet {
    ICouriersService ics = new CouriersServiceImpl();
    IAdminService ias=new AdminServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        int index = requestURI.lastIndexOf("/")+1;
        String mName=requestURI.substring(index);
        Class cla = this.getClass();
        Method method=null;
        try{
            method = cla.getMethod(mName, HttpServletRequest.class, HttpServletResponse.class);
            resp.setContentType("application/json;charset=utf-8");
            req.setCharacterEncoding("utf-8");
            method.invoke(this,req,resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public void showdt(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        String id = req.getParameter("id");
        PageHelper ph=new PageHelper();
        ph.setDateCount(ias.queryAllDataCount(id));
        ph.setPageIndex(Integer.parseInt(req.getParameter("indexpage")));
        ArrayList<Packages> packages = ias.queryAllPackages(id,ph);
        System.out.println(packages.get(0).getId());
        ph.setListIndex(packages);
        resp.getWriter().println(new Gson().toJson(ph));
    }


    public void showcouriers(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PageHelper ph=new PageHelper();
        ph.setDateCount(ics.queryDataCount());
        ph.setPageIndex(Integer.parseInt(req.getParameter("indexpage")));
        ArrayList<Couriers> packages = ics.queryAll(ph);
        ph.setListIndex(packages);
        resp.getWriter().println(new Gson().toJson(ph));
    }

    public void showusers(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PageHelper ph=new PageHelper();
        ph.setDateCount(ias.queryDataCount());
        ph.setPageIndex(Integer.parseInt(req.getParameter("indexpage")));
        ArrayList<Users> users = ias.selectAllUsers(ph);
        String password1=null;
        int index=0;
        for(Users u:users){
            String password = users.get(index).getPassword();
            String cKey = "xy;SHUPIAN66+-=+";
            try {
               password1 = LoginController.Decrypt(password, cKey);
            } catch (Exception e) {
                e.printStackTrace();
            }
            users.get(index).setPassword(password1);
            index++;
        }
        ph.setListIndex(users);
        resp.getWriter().println(new Gson().toJson(ph));
    }

    public void delusers(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        boolean b = ias.delUsers(username);
        resp.getWriter().println(new Gson().toJson(b));
    }

    public void updateusers(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String role = req.getParameter("role");
        String cKey = "xy;SHUPIAN66+-=+";
        String password1=null;
        try {
            password1 = LoginController.Encrypt(password, cKey);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Users users =new Users();
            users.setUsername(username);
            users.setPassword(password1);
            users.setRole(role);
        System.out.println(username+":"+password+":"+role);
        boolean b = ias.updateUsers(users);
        resp.getWriter().println(new Gson().toJson(b));
    }

    //加密算法
    public static String Encrypt(String sSrc, String sKey) throws Exception {
        if (sKey == null) {
            System.out.print("Key为空null");
            return null;
        }
        // 判断Key是否为16位
        if (sKey.length() != 16) {
            System.out.print("Key长度不是16位");
            return null;
        }
        byte[] raw = sKey.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
        return new BASE64Encoder().encode(encrypted);//此处使用BASE64做转码功能，同时能起到2次加密的作用。
    }

    //解密算法
    public static String Decrypt(String sSrc, String sKey) throws Exception {
        try {
            // 判断Key是否正确
            if (sKey == null) {
                System.out.print("Key为空null");
                return null;
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
                System.out.print("Key长度不是16位");
                return null;
            }
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);//先用base64解密
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original,"utf-8");
                return originalString;
            } catch (Exception e) {
                System.out.println(e.toString());
                return null;
            }
        } catch (Exception ex) {
            System.out.println(ex.toString());
            return null;
        }
    }
}
